
import { AppDataSource } from '@/config/AppDataSource';
import { CreateArticleDto, UpdateArticleDto, QueryArticleDto, DeleteArticleDto } from '@/dto/article.dto';
import { Article } from '@/entities/article.entity';
import { In } from 'typeorm';
export class ArticleRepository {
    private repositor = AppDataSource.getRepository(Article);
    constructor() { }

    async findExcludeId(data: UpdateArticleDto) {
        const conflictCategory = await this.repositor
            .createQueryBuilder('article')
            .where('article.id != :id', { id: data.id })
            .andWhere('(article.title = :title)', { title: data.title })
            .getOne();
        return conflictCategory
    }


    async articleExists(title: string) {
        const c = await this.repositor.findOne({
            where: [
                { title },
            ],
        });
        return c;
    }

    async findById(id: number) {

        const item = await this.repositor.findOneBy({
            id
        })
        return item;
    }

    async create(data: CreateArticleDto): Promise<Article> {
        const article = new Article();
        article.title = data.title;
        article.comment = data.comment!;
        article.content = data.content!;
        article.coverImage = data.coverImage!;
        article.status = data.status!;
        article.userId = data.userId!;
        article.categoryId = data.categoryId!;
        const result = await this.repositor.save(article)
        // console.log("result", result)
        return result;
    }
    async update(data: UpdateArticleDto) {
        const article = new Article();

        article.title = data.title;
        article.comment = data.comment!;
        article.id = data.id;
        article.content = data.content!;
        article.coverImage = data.coverImage!;
        article.status = data.status!;
        article.userId = data.userId!;
        article.categoryId = data.categoryId!;



        return this.repositor.save(article);

    }



    async selectList(reqData: QueryArticleDto) {
        const { page, pageSize, title, orderBy, categoryId, comment,status } = reqData;

        const queryBuilder = this.repositor
            .createQueryBuilder('article')
            .select([
                'article.id',
                'article.title',
                'article.categoryId',
                'article.comment',
                'article.createdAt',
                'article.updatedAt',
                'article.viewCount',
                'article.userId',
                'article.status',

            ]);

        if (title) {
            queryBuilder.andWhere('article.title LIKE :title', { title: `%${title}%` });
        }
        if (comment) {
            queryBuilder.andWhere('article.comment LIKE :comment', { comment: `%${comment}%` });
        }
        if (categoryId) {
            queryBuilder.andWhere('article.categoryId = :categoryId', { categoryId });
        }
        if (status) {
            queryBuilder.andWhere('article.status = :status', { status });
        }

        const [sortBy, sortOrder] = orderBy.split(" ")
        const [article, total] = await queryBuilder
            .orderBy(`article.${sortBy}`, sortOrder.toLocaleUpperCase() as "ASC" | "DESC")
            .skip((page - 1) * pageSize)
            .take(pageSize)
            .getManyAndCount();
            // console.log(queryBuilder.getQuery()); 
        return {
            list: article,//.map(article => new CategoryResponseDto(article)),
            total,
            page,
            pageSize,
            totalPages: Math.ceil(total / pageSize),
        };


    }
    async delete(reqData: DeleteArticleDto) {
        const result = await this.repositor.delete({
            id: In(reqData.ids)
        });
        return !!result.affected;

    }

}

export default new ArticleRepository();